from django.db import models
from django.contrib.auth import get_user_model
from rest_framework.exceptions import ValidationError

User = get_user_model()


class Category(models.Model):
    """图片分类"""
    name = models.CharField(max_length=128, unique=True)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name


class Tag(models.Model):
    """图片标签"""
    name = models.CharField(max_length=32, unique=True)

    def __str__(self):
        return self.name


class Album(models.Model):
    """图集/相册"""
    title = models.CharField(max_length=256)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='albums')

    def __str__(self):
        return self.title


def validate_image_size(image):
    max_size_kb = 5 * 1024
    if image.size > max_size_kb * 1024:
        raise ValidationError(f"图片不能大于 {max_size_kb}KB")


class Photo(models.Model):
    """单张图片"""
    title = models.CharField(max_length=256)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='photos/%Y/%m/%d/', validators=[validate_image_size])
    uploaded_at = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='photos')
    tags = models.ManyToManyField(Tag, blank=True, related_name='photos')
    album = models.ForeignKey(Album, on_delete=models.SET_NULL, null=True, blank=True, related_name='photos')
    uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='photos')  # 上传者

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-uploaded_at']
